package com.iwunu.gateway.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.iwunu.gateway.entity.OrgUser;
import com.iwunu.gateway.service.FlockOrgService;
import com.iwunu.gateway.service.TokenService;
import com.iwunu.gateway.vo.OrgVo;
import com.iwunu.iot.common.constant.ResultCodeEnum;
import com.iwunu.iot.common.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiParam;

@RestController
@Api(value = "fackLock/org", tags = "商户信息API")
public class OrgApiController {
	@Autowired
	private FlockOrgService flockOrgService;
	@Autowired
	private TokenService tokenService;	
	/**
     **添加商户
     * @return
     */
	@RequestMapping(value = "org/add" , method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Result> save(
    		 @RequestBody OrgVo orgvo
            ){
    	 Result result = null ;
    		 OrgUser org = flockOrgService.save(orgvo); 
    	 result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(),org);
    	 return new ResponseEntity<>(result, HttpStatus.OK);
    }
	/**
     **修改用户
     * @return
     */
	@RequestMapping(value = "org/update" , method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Result> update(
   		 	 @RequestHeader String Authorization,
             @ApiParam(value = "修改密码", required = true)@RequestParam String password
            ){
    	 Result result = null ;
    	 String userId = tokenService.parseToken(Authorization);
    	 OrgUser org = flockOrgService.getOrgUserByUserId(userId);
    	 if(org==null) {
           	 result = new Result(ResultCodeEnum.USER_NOTEIXT.getCode(), ResultCodeEnum.USER_NOTEIXT.getDesc(),null);
           	 return new ResponseEntity<>(result, HttpStatus.OK); 
    	 }
    	 OrgUser user =  flockOrgService.update(org,password);
    	 if(user ==null) {
        	 result = new Result(ResultCodeEnum.SAVE_FALSE.getCode(), ResultCodeEnum.SAVE_FALSE.getDesc(),null);
        	 return new ResponseEntity<>(result, HttpStatus.CREATED);
    	 }
    	 result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(),user);
    	 return new ResponseEntity<>(result, HttpStatus.OK);
    }
}
